#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    sendCount = 0;
    ui->lineEdit->setStyleSheet("QLineEdit { background: transparent; border-width: 0; border-style: outset; }");
    ui->lineEdit_2->setStyleSheet("QLineEdit { background: transparent; border-width: 0; border-style: outset; }");
    ui->lineEdit_3->setStyleSheet("QLineEdit { background: transparent; border-width: 0; border-style: outset; }");
    initUdpTest();
    timer1 = new QTimer(this);
    qDebug() << "定时器启动"<<ui->interval->currentText();
    connect(timer1, &QTimer::timeout, this, &MainWindow::sendDataToST);
    
}

MainWindow::~MainWindow()
{
     // 停止并等待线程结束
    recvThread8066->quit();
    recvThread8066->wait();
    recvThread8067->quit();
    recvThread8067->wait();
    sendThread->quit();
    sendThread->wait();

    delete ui;
}



/*

    用于发射和接收数据-》UDP通信

*/


//单次发送数据给昇腾槽函数
void MainWindow::on_btnSend_clicked()
{
    QString num;
    if(ui->checkBox->isChecked()){
        num = ui->lineEdit_5->text();
    }
    if (!timer1->isActive()) {  // 避免重复启动
        double interval = ui->interval->currentText().toDouble();  // 获取下拉框选择的间隔时间
        timer1->start(interval*1000);
    }
}


void MainWindow::sendDataToST()
{   
    sendCount++;
    QString data = ui->txtInput->toPlainText();
    ui->textShow->appendPlainText(data);
    QString checkMark = QString::fromUtf8("\u2714");
    ui->textShow3->appendPlainText(checkMark);
    qDebug() << "发送数据：" << data;
    
    //udpSend->sendData(data.toUtf8(), QHostAddress("192.168.80.1"), 8081);
    // 发送信号给发送线程
    emit sendDataSignal(data.toUtf8(), QHostAddress("192.168.80.1"), 8081);
    
    if(sendCount == ui->lineEdit_5->text().toInt()||ui->lineEdit_5->text().toInt() ==0)
    {
        if (timer1->isActive()) {
            timer1->stop();
            qDebug() << "定时器已停止";
        }
        sendCount = 0;
    }
}

//初始化UDP测试端口槽函数
void MainWindow::initUdpTest()
{  
    //初始化8066
    recvThread8066 = new QThread(this);
    udpRecv8066 = new UdpComm(8066,this);
    udpRecv8066->moveToThread(recvThread8066);
    connect(recvThread8066, &QThread::finished, udpRecv8066, &QObject::deleteLater);
    connect(udpRecv8066, &UdpComm::dataReceived, this, [this](const QByteArray &data, const QHostAddress &addr, quint16 port) {
        qDebug() << "收到数据：" << data << " 来自：" << addr.toString() << ":" << port;
    });
    connect(udpRecv8066, &UdpComm::errorOccurred, this, [this](const QString &err) {
        QMessageBox::warning(this, "UDP错误", err);
    });
    recvThread8066->start();


    // 初始化接收端口8067
     recvThread8067 = new QThread(this);
    udpRecv8067 = new UdpComm(8067, this);
    udpRecv8067->moveToThread(recvThread8067);
    connect(recvThread8067, &QThread::finished, udpRecv8067, &QObject::deleteLater);
    connect(udpRecv8067, &UdpComm::errorOccurred, this, [this](const QString &err) {
        QMessageBox::warning(this, "UDP8067错误", err);
    });
    // 绑定到8067端口的未解析接收信号，显示到textshow2中
    connect(udpRecv8067, &UdpComm::dataReceived, this, [this](const QByteArray &data) {
        ui->textShow2->appendPlainText(QString::fromLatin1(data));
    });
    connect(udpRecv8067, &UdpComm::dataReceived, this, &MainWindow::receive_parseSonarData);
    recvThread8067->start();


    // 绑定到8067端口解析后的数据,显示到textshow4中
    connect(this, &MainWindow::parsedDataReady, this, &MainWindow::output_parseSonarData);


// 初始化发送线程
    sendThread = new QThread(this);
    udpSend = new UdpSender(this);
    udpSend->moveToThread(sendThread);
    // 在initUdpTest中连接发送信号
    connect(this, &MainWindow::sendDataSignal, udpSend, &UdpSender::sendData, Qt::QueuedConnection);
    connect(sendThread, &QThread::finished, udpSend, &QObject::deleteLater);
    connect(udpSend, &UdpSender::errorOccurred, this, [this](const QString &err) {
        QMessageBox::warning(this, "发送错误", err);
    });
    sendThread->start();
    // 初始化发送端口（临时测试用）
    //udpSend = new UdpComm(0, this); // 发送端口随机，不绑定固定端口

}



/*

    用于将昇腾传入的16位数据解析后回显屏幕


*/
void MainWindow::output_parseSonarData(int distance, int angle, const QString &targetType)
{
     
    ui->textShow4->appendPlainText(QString(" 识别到了%1  距离：%2   角度：%3")
                              .arg(targetType).arg(distance).arg(angle));

}

void MainWindow::receive_parseSonarData(const QByteArray &data)
{
    MainWindow::parseSonarData(data);
}

void MainWindow::parseSonarData(const QByteArray &data)
{
    QString receivedMsg = QString::fromLatin1(data);
    if (receivedMsg.length() < 15) return;
  //  qDebug() << receivedMsg.length() ;
    QString dataMessage = receivedMsg.mid(2);
   // if (dataMessage.length() < 15) return;
  //  qDebug() << dataMessage ;
    QString distBin = dataMessage.mid(2, 5);  // 距离二进制段（5位）
    QString angleBin = dataMessage.mid(8, 5); // 角度二进制段（5位）
    QString typeBin = dataMessage.mid(12, 3); // 目标类型二进制段（3位）
   // qDebug() << "成功3" ;
    int distance = distBin.toInt(nullptr, 2) * 5 + 5;   // 距离计算
    int angle = angleBin.toInt(nullptr, 2) * 5 + 5;     // 角度计算
    QString targetType;
    // 目标类型映射（原代码注释部分，可根据实际需求补充）
    /*
    switch (typeBin.toInt(nullptr, 2)) {
        case 0: targetType = "AUV"; break;
        case 1: targetType = "球"; break;
        // ... 其他类型
        default: targetType = "未知";
    }
    */
    targetType = "Fish"; // 原代码默认类型
    emit parsedDataReady(distance, angle, targetType);
    //return ("解析结果：距离"+distance+"角度"+angle+"类型"+targetType);
    qDebug() << "解析结果：距离" << distance << " 角度" << angle << " 类型" << targetType;
  // qDebug() << "成功" ;
}





void MainWindow::on_checkBox_stateChanged(int arg1)
{  
    QString num;
   // qDebug() << "arg1" << arg1;
    if(arg1 ==2&&num!= nullptr)
    {
        num = ui->lineEdit_5->text();
        int n =num.toInt();
        qDebug() << "n" << n;
        MainWindow::total_send_count = n;
    }
    else
        return;

}


void MainWindow::on_button1_clicked()
{
     if (timer1->isActive()) {  // 只在运行时停止
        timer1->stop();
        qDebug() << "定时器已停止"<<ui->lineEdit_5->text().toInt() <<sendCount;
    }
}

